<?php

class LoginController extends Zend_Controller_Action
{
	private $_form;
	
	public function init(){
		$this->_form = new Form_Login();
	}
	
	public function indexAction(){
		$this->_forward('login');
	}
	
	public function loginAction(){
		
	    if ( $this->getRequest()->isPost() ) {

			$formData = $this->getRequest()->getPost();
			
			if ( $this->_form->isValid($formData) ) {
				
			    //username en password vanuit het formulier ophalen en in variablen stoppen
		    	$username = $this->_form->getValue( 'username' );
		    	$password = $this->salt( $this->_form->getValue( 'password' ) ); //hashen want we willen niet de wachtwoorden opslaan
		    	$password = $this->_form->getValue( 'password' );
				
		    	//auth aanroepen om te kijken of de user wel mag inloggen
		    	$authResult = $this->auth($username, $password);
		    	
		    	if(!$authResult->isValid()){
		    	    $this->_form->setDescription('Invalid Credentials Provided');
		    	} else {
		    		$this->_helper->redirector('list', 'klacht');
		    	}
			}
	    }
			
		$this->view->form = $this->_form;
		
	}
	
	public function logoutAction()
	{
		$this->getHelper('viewRenderer')->setNoRender();
		//Zend_Session::destroy(); dit werkt nog niet moet ik nog even naar kijken
		Zend_Auth::getInstance()->clearIdentity();
        $this->_helper->redirector('index'); // back to login page
	}
	
	private function auth( $username = NULL, $password = NULL ){
	    
	    if(is_null( $username ) || is_null( $password )){
			throw new exception( 'Application Error' );
		}
		
		//Zend_Auth laden voor authenticatie
		$auth = Zend_Auth::getInstance();
		
		//database adapter ophalen uit het register (gezet in de bootstrapper)
		$dbAdapter = Zend_Registry::get('db');
		
		//authadapter aanmaken zodat er straks kan worden geverifierd tegen over een table
		$authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);
		$authAdapter
		    ->setTableName( 'user' )
		    ->setIdentityColumn( 'username' )
		    ->setCredentialColumn( 'password' );
		
		$authAdapter
			->setIdentity( $username )
		    ->setCredential( $password );
		
		$result =  $auth->authenticate( $authAdapter );
		
		$user = $authAdapter->getResultRowObject();
		
		$authSession = new Zend_Session_Namespace('Zend_Auth', true);
		$authSession->userGroup = $user->usertype;
		$authSession->userId = $user->id;
		$authSession->username = $user->username;
		
		//authenticate de ingekomen gegevens en return deze    
		return $auth->authenticate( $authAdapter );

	}
	
	private function salt($password, $salt="ZH10"){
		
		//hier moet de salt plaats vinden
		$saltedpassword = sha1("{".$salt ."}".  $password);
		return $saltedpassword;
	}
	
}
